package com.thx.common.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 数据源拦截器.
 *
 * @author balance
 */
@Component
@Aspect
@Order(-2000)
public class DataSourceInterceptor {
  private static Logger log = LoggerFactory.getLogger(DataSourceInterceptor.class);

  @Pointcut("execution(public * com.thx..service..*(..)) || "
      + "execution(public * com.topdt..service..*(..))")
  private void anyMethod() {}// 定义一个切入点

  /**
   * 确定数据源.
   *
   * @param pjp 进入点
   */
  @Around("anyMethod()")
  public Object determineDataSource(ProceedingJoinPoint pjp) throws Throwable {
    log.debug("进入动态设置数据源方法………………");

    Class<? extends Object> clasz = pjp.getTarget().getClass();

    DataSource dataSource = clasz.getAnnotation(DataSource.class);
    if (dataSource != null) {
      String dataSourceType = dataSource.value();
      DynamicDataSourceContextHolder.setDataSourceType(dataSourceType);
      log.debug(clasz.getName() + "指定的数据源为：" + dataSourceType);
    } else {
      log.debug(clasz.getName() + "使用默认数据源。");
    }

    Object object = null;
    try {
      object = pjp.proceed();// 执行该方法
    } finally {
      DynamicDataSourceContextHolder.clearDataSourceType();
    }

    log.debug("………………动态设置数据源切面AOP 结束");
    return object;
  }
}
